package cn.tedu.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {
    @Autowired
    private DataSource ds;

    public static void main(String[] args) {
        SpringApplication.run(DbInitApplication.class, args);
    }

    /*
        spring流程，启动实例->依赖注入->postconstruct(初始化方面的工作)->后续工作
     */
    @PostConstruct
    public void init() throws SQLException {
        exec("sql/account.sql");
        exec("sql/order.sql");
        exec("sql/seata-server.sql");
        exec("sql/storage.sql");
    }

    private void exec(String sql) throws SQLException {
        // C:\TCGBV\codes\seata-at\db-init\target\classes\sql\account.sql
        ClassPathResource cpr = new ClassPathResource(sql, DbInitApplication.class.getClassLoader());

        EncodedResource resource = new EncodedResource(cpr, "UTF-8");

        // spring jdbc 提供的 ScriptUtils 工具，来执行 sql 脚本
        ScriptUtils.executeSqlScript(ds.getConnection(), resource);
    }
}
